<?php

ini_set('display_errors', 'On');
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

use think\facade\Db;

require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../vendor/topthink/framework/src/helper.php';

define('DS', DIRECTORY_SEPARATOR);
define('ROOT_PATH', __DIR__.DS.'..'.DS);
define('INSTALL_PATH', ROOT_PATH.'database'.DS.'install'.DS);
define('CONFIG_PATH', ROOT_PATH.'config'.DS);
define('ENV_PATH', ROOT_PATH.DS);

$currentHost = ($_SERVER['SERVER_PORT'] == 443 ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].'/';



function isReadWrite($file)
{
    if (DIRECTORY_SEPARATOR == '\\') {
        return true;
    }
    if (DIRECTORY_SEPARATOR == '/' && @ ini_get("safe_mode") === false) {
        return is_writable($file);
    }
    if (!is_file($file) || ($fp = @fopen($file, "r+")) === false) {
        return false;
    }
    fclose($fp);

    return true;
}

$errorInfo = null;
$env_temp  = @parse_ini_file(ENV_PATH.DS.'.env', true);
if (is_file(INSTALL_PATH.'lock'.DS.'install.lock')) {
    $errorInfo = '已安装系统，如需重新安装请删除文件：/database/install/lock/install.lock';
} elseif (!isReadWrite(ROOT_PATH.'config'.DS)) {
    $errorInfo = ROOT_PATH.'config'.DS.'：读写权限不足';
} elseif (!isReadWrite(ROOT_PATH.'runtime'.DS)) {
    $errorInfo = ROOT_PATH.'runtime'.DS.'：读写权限不足';
} elseif (!isReadWrite(ROOT_PATH.'public'.DS)) {
    $errorInfo = ROOT_PATH.'public'.DS.'：读写权限不足';
} elseif (!checkPhpVersion('7.1.0')) {
    $errorInfo = 'PHP版本不能小于7.1.0';
} elseif (!extension_loaded("PDO")) {
    $errorInfo = '当前未开启PDO，无法进行安装';
} elseif ($env_temp && $env_temp['SYSTEM'] == 'product' ){
    $errorInfo = '非法请求';
}

if($errorInfo != null){
    exit($errorInfo);
}

// POST请求
if (isAjax()) {

    $post = $_POST;
    $resource_url = '//img.vrupup.com/resources/0_frame_source/';
    $cover      = false;
    $database   = $post['develop']['db_name'];
    $hostname   = $post['develop']['db_host'];
    $hostport   = $post['develop']['db_port'];
    $dbUsername = $post['develop']['db_user'];
    $dbPassword = $post['develop']['db_pass'];
    $prefix     = $post['develop']['db_pre'];
    $username   = $post['develop']['username'];
    $password   = $post['develop']['password'];


    // DB类初始化
    $config = [
        'type'     => 'mysql',
        'hostname' => $hostname,
        'username' => $dbUsername,
        'password' => $dbPassword,
        'hostport' => $hostport,
        'charset'  => 'utf8',
        'prefix'   => $prefix,
        'debug'    => true,
    ];
    Db::setConfig([
        'default'     => 'mysql',
        'connections' => [
            'mysql'   => $config,
            'install' => array_merge($config, ['database' => $database]),
        ],
    ]);

    // 检测数据库连接
    if (!checkConnect()) {
        $data = [
            'code' => 0,
            'msg'  => '数据库连接失败',
        ];
        die(json_encode($data));
    }
    // 检测数据库是否存在
    if (!$cover && checkDatabase($database)) {
        $data = [
            'code' => 0,
            'msg'  => '数据库已存在，请选择覆盖安装或者修改数据库名',
        ];
        die(json_encode($data));
    }
    // 创建数据库
    createDatabase($database);
    // 导入sql语句等等
    $install = install($username, $password, array_merge($config, ['database' => $database]));
    if ($install !== true) {
        $data = [
            'code' => 0,
            'msg'  => '系统安装失败：'.$install,
        ];
        die(json_encode($data));
    }
    $url=dirname('http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]);
    $data = [
        'code' => 1,
        'msg'  => '系统安装成功',
        'url'  => $url,
    ];
    die(json_encode($data));
}


    /**
     * 写入env文件
     * @param $env_path
     * @param $config
     * @date 2020/8/6 16:37
     */
function write_env($env_path, $config) {
        foreach($config as $key=>$value) {
            if(is_array($value)) {
                file_put_contents($env_path, "[{$key}]\n", FILE_APPEND);
                foreach($value as $k=>$v) {
                    file_put_contents($env_path, "{$k}='{$v}'\n", FILE_APPEND);
                }
            }else {
                file_put_contents($env_path, "{$key}='{$value}'\n", FILE_APPEND);
            }
        }
        file_put_contents($env_path, "\n", FILE_APPEND);
    }

function isAjax()
{
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        return true;
    } else {
        return false;
    }
}

function checkPhpVersion($version)
{
    $php_version = explode('-', phpversion());
    $check       = strnatcasecmp($php_version[0], $version) >= 0 ? true : false;

    return $check;
}

function checkConnect()
{
    try {
        Db::query("select version()");
    } catch (\Exception $e) {
        return false;
    }

    return true;
}

function checkDatabase($database)
{
    $check = Db::query("SELECT * FROM information_schema.schemata WHERE schema_name='{$database}'");
    if (empty($check)) {
        return false;
    } else {
        return true;
    }
}

function createDatabase($database)
{
    try {
        Db::execute("CREATE DATABASE IF NOT EXISTS `{$database}` DEFAULT CHARACTER SET utf8");
    } catch (\Exception $e) {
        return false;
    }

    return true;
}

function parseSql($sql, $to, $from)
{
    [$pure_sql, $comment] = [[], false];
    $sql = explode("\n", trim(str_replace(["\r\n", "\r"], "\n", $sql)));
    foreach ($sql as $key => $line) {
        if ($line == '') {
            continue;
        }
        if (preg_match("/^(#|--)/", $line)) {
            continue;
        }
        if (preg_match("/^\/\*(.*?)\*\//", $line)) {
            continue;
        }
        if (substr($line, 0, 2) == '/*') {
            $comment = true;
            continue;
        }
        if (substr($line, -2) == '*/') {
            $comment = false;
            continue;
        }
        if ($comment) {
            continue;
        }
        if ($from != '') {
            $line = str_replace('`'.$from, '`'.$to, $line);
        }
        if ($line == 'BEGIN;' || $line == 'COMMIT;') {
            continue;
        }
        array_push($pure_sql, $line);
    }
    $pure_sql = implode("\n", $pure_sql);

    return explode(";\n", $pure_sql);
}

function install($username, $password, $config)
{
    $sqlPath  = file_get_contents(INSTALL_PATH.'install.sql');
    $sqlArray = parseSql($sqlPath, $config['prefix'], 'm_');
    Db::startTrans();
    try {
        foreach ($sqlArray as $vo) {
            Db::connect('install')->execute($vo);
        }
        $pwd = password(md5($password));
        Db::connect('install')
            ->name('admin')
            ->insert([
                'id'            => md5(mt_rand(100000, 999999).microtime()),
                'name'          => $username,
                'is_root'       => 1,
                'password'      => $pwd['password'],
                'password_salt' => $pwd['salt'],
                'create_time'   => time(),
                'create_ip'     => '127.0.0.1',
            ]);

        // 处理安装文件
        !is_dir(INSTALL_PATH) && @mkdir(INSTALL_PATH);
        !is_dir(INSTALL_PATH.'lock'.DS) && @mkdir(INSTALL_PATH.'lock'.DS);
        @file_put_contents(ENV_PATH.'.env', getEnvConfig($config));
        @file_put_contents(INSTALL_PATH.'lock'.DS.'install.lock', date('Y-m-d H:i:s'));
        @file_put_contents(CONFIG_PATH.'extra.php', getExtraConfig());
        Db::commit();
    } catch (\Exception $e) {
        Db::rollback();

        return $e->getMessage();
    }

    return true;
}

function password($password)
{
    $len             = 6;
    $pool            = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
    $str             = substr(str_shuffle(str_repeat($pool, intval(ceil($len / strlen($pool))))), 0, $len);
    $pwd             = [];
    $pwd['salt']     = $str;
    $pwd['password'] = md5(md5($password.$pwd['salt']).'doimetp3qwz6dbnpuu12v5fe845l17gk');

    return $pwd;
}

function getEnvConfig($data)
{
    $token_key = date('Y').date('m').date('d').date('His').time().rand(11111,99999);
    $token_iss = 'Admin'.rand(11111,99999);
    if(!empty($_POST['oss_open'])){
        $upload_type = 'oss';
    }elseif(!empty($_POST['cos_open'])){
        $upload_type = 'cos';
    }elseif(!empty($_POST['aws_open'])){
        $upload_type = 'aws';
    }elseif(!empty($_POST['qiniu_open'])){
        $upload_type = 'qiniu';
    }else{
        $upload_type = 'local';
    }
    // 写入OSS配置
    if(!empty($_POST['oss_open'])) {
        $upload_config = <<<EOF
        oss_bucket         = 'pilihuo'
        oss_key_id         = 'LTAI5tPE7WniQCzNMotP9DEG'
        oss_key_secret     = 'IBO7rKKWMBwJkDaCm9UWQgvAf3wkp2'
        oss_upload_url     = 'http://oss-cn-hangzhou.aliyuncs.com'
        oss_static_url     = 'https://img.vrupup.com/'
        oss_static_path    =  '{$_POST['oss_dir']}'
        oss_storage_region = 'oss-cn-hangzhou'
EOF;
    }
    // 写入COS配置
    if(!empty($_POST['cos_open'])) {
    $upload_config = <<<EOF
    cos_bucket        = 'img-hpjy-1252554569'
    cos_secret_id     = 'AKIDjGwNcdh5RcbMqJkIMBuUrwE3FCuPmQ0O'
    cos_secret_key    = 'PmwchaHkxuZxteohI4yEEwnqBFmjtKUR'
    cos_region        = 'ap-beijing'
    cos_static_url    = 'https://hpjyimg.vrupup.com'
    cos_static_path   =  '{$_POST['cos_dir']}'
EOF;
    }

    // 写入AWS配置
    if(!empty($_POST['aws_open'])) {
        $upload_config = <<<EOF
        aws_bucket       = 'prd-bd-growrice'
        aws_key_id       = 'AKIAXTYW5IFALNLI3Z6O'
        aws_key_secret   = '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'
        aws_region       = 'cn-northwest-1'
        aws_static_path  = '{$_POST['aws_dir']}'
EOF;
    }

    // 写入七牛配置
    if(!empty($_POST['qiniu_open'])) {
        $upload_config = <<<EOF
        qiniu_bucket      = 'pilihuo',
        qiniu_key_id      = 'qYiwSuQ1Z-_LnzF4sQN7rw-wElnl3qMy_g0s0wSy',
        qiniu_key_secret  = '6KymgN9rhjhoEcKR8StFfL-5l7Ji-2RNsGwOHEV7',
        qiniu_static_url  = 'http://r4o39bpfl.hn-bkt.clouddn.com/',
EOF;
}
return <<<EOT
    SYSTEM='local'
    resource_url='//game.vrupup.com/resources/0_frame_source/'
    APP_DEBUG = true
    TOKEN_KEY='$token_key'
    TOKEN_ISS=$token_iss
    upload_type='{$upload_type}'
    
{$upload_config}
 
    applet_app_id  = ''
    applet_app_secret = ''
    applet_key = ''
    applet_mch_id = ''
    
[product]
    db_host='rm-bp1p153yeb567lpo0.mysql.rds.aliyuncs.com' 
    db_port='3306'
    db_char='utf8mb4'
    db_name=''
    db_user=''
    db_pass=''
    db_pre=''
    redis_host='r-bp18vmtk1409q08i00.redis.rds.aliyuncs.com'
    redis_port='6379'
    redis_pass='1yVXE0uOItLIBCE'
    redis_index='{$_POST['develop']['redis_index']}'
    
[develop]
    db_host='rm-bp1p153yeb567lpo0.mysql.rds.aliyuncs.com'
    db_port='3306'
    db_char='utf8mb4'
    db_name=''
    db_user=''
    db_pass=''
    db_pre=''
    redis_host='r-bp18vmtk1409q08i00.redis.rds.aliyuncs.com'
    redis_port='6379'
    redis_pass='1yVXE0uOItLIBCE'
    redis_index='{$_POST['develop']['redis_index']}'
    
[local]
    db_host='127.0.0.1'
    db_port='3306'
    db_char='utf8mb4'
    db_name='{$_POST['develop']['db_name']}'
    db_user='{$_POST['develop']['db_user']}'
    db_pass='{$_POST['develop']['db_pass']}'
    db_pre= '{$_POST['develop']['db_pre']}'
    redis_host='127.0.0.1'
    redis_port='6379'
    redis_pass=''
    redis_index='{$_POST['develop']['redis_index']}'
    static_url=''
    static_path='{$_POST['local_dir']}'
    
EOT;
}

function getExtraConfig()
{
    return <<<EOT
<?php
# +----------------------------------------------------------------------
# | extra配置
# +----------------------------------------------------------------------

return [
    'auth'     => [
        // token过滤
        'token_filter'      => [
            'login.login',
            'login.captcha',
        ],
        // 权限过滤
        'permission_filter' => [
            'login.login',
            'login.captcha',
            'login.loginOut',
            'login.info',
        ],
    ],
    // 密码加盐
    'passport' => [
        'password_salt' => 'doimetp3qwz6dbnpuu12v5fe845l17gk',
    ],
];

EOT;
}

function getAppConfig()
{
    return <<<EOT
<?php
// +----------------------------------------------------------------------
// | 应用设置
// +----------------------------------------------------------------------

return [
    // 应用地址
    'app_host'         => env('app.host', ''),
    // 应用的命名空间
    'app_namespace'    => '',
    // 是否启用路由
    'with_route'       => true,
    // 默认应用
    'default_app'      => 'index',
    // 默认时区
    'default_timezone' => 'Asia/Shanghai',

    // 应用映射（自动多应用模式有效）
    'app_map'          => [],
    // 域名绑定（自动多应用模式有效）
    'domain_bind'      => [],
    // 禁止URL访问的应用列表（自动多应用模式有效）
    'deny_app_list'    => [],

    // 异常页面的模板文件
    'exception_tmpl'   => app()->getThinkPath().'tpl/think_exception.tpl',

    // 错误显示信息,非调试模式有效
    'error_message'    => '页面错误！请稍后再试～',
    // 显示错误信息
    'show_error_msg'   => false,
];

EOT;
}

function getDatabaseConfig($data)
{
    return <<<EOT
<?php

return [
    // 默认使用的数据库连接配置
    'default'         => env('database.driver', 'mysql'),

    // 自定义时间查询规则
    'time_query_rule' => [],

    // 自动写入时间戳字段
    // true为自动识别类型 false关闭
    // 字符串则明确指定时间字段类型 支持 int timestamp datetime date
    'auto_timestamp'  => true,

    // 时间字段取出后的默认时间格式
    'datetime_format' => 'Y-m-d H:i:s',

    // 数据库连接配置信息
    'connections'     => [
        'mysql' => [
            // 数据库类型
            'type'              => env('database.type', 'mysql'),
            // 服务器地址
            'hostname'          => env('database.hostname', '{$data['hostname']}'),
            // 数据库名
            'database'          => env('database.database', '{$data['database']}'),
            // 用户名
            'username'          => env('database.username', '{$data['username']}'),
            // 密码
            'password'          => env('database.password', '{$data['password']}'),
            // 端口
            'hostport'          => env('database.hostport', '{$data['hostport']}'),
            // 数据库连接参数
            'params'            => [],
            // 数据库编码默认采用utf8
            'charset'           => env('database.charset', 'utf8'),
            // 数据库表前缀
            'prefix'            => env('database.prefix', '{$data['prefix']}'),

            // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
            'deploy'            => 0,
            // 数据库读写是否分离 主从式有效
            'rw_separate'       => false,
            // 读写分离后 主服务器数量
            'master_num'        => 1,
            // 指定从服务器序号
            'slave_no'          => '',
            // 是否严格检查字段是否存在
            'fields_strict'     => true,
            // 是否需要断线重连
            'break_reconnect'   => false,
            // 监听SQL
            'trigger_sql'       => env('app_debug', true),
            // 开启字段缓存
            'fields_cache'      => false,
            // 字段缓存路径
            'schema_cache_path' => app()->getRuntimePath() . 'schema' . DIRECTORY_SEPARATOR,
        ],
        'redis' =>[
            'type' => 'redis',
            // 服务器地址
            'hostname'        => Env::get(SYSTEM.'.redis_host', '127.0.0.1'),
            // 数据库名
            'database'        => Env::get(SYSTEM.'.redis_index', ''),
            // 密码
            'password'        => Env::get(SYSTEM.'.redis_pass', ''),
            // 端口
            'hostport'        => Env::get(SYSTEM.'.redis_port', '6379'),

            'timeout'         => Env::get(SYSTEM.'.redis.timeout', 0),

            'prefix'          => Env::get(SYSTEM.'.redis_index', 'sam_'),
        ]
        // 更多的数据库配置信息
    ],
];

EOT;
}


?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>安装后台程序</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <!-- <link rel="stylesheet" type="text/css" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css"/>
    <link rel="stylesheet" href="static/css/install.css" media="all"> -->
    <link href="//unpkg.com/layui@2.9.8/dist/css/layui.css" rel="stylesheet">
    <link rel="stylesheet" href="//img.vrupup.com/resources/0_frame_source/layuiadmin/style/admin.css" media="all">
    <link rel="stylesheet" href="//img.vrupup.com/resources/0_frame_source/layuiadmin/style/login.css" media="all">
    <link rel="stylesheet" href="//img.vrupup.com/resources/0_frame_source/admin/css/login.css" media="all">
</head>
<body>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md1"></div>
        <div class="layui-card layui-col-md10">
            <div class="layui-card-header">三国服务器 THINKPHP-6.0 自动化后台3.0  - Step1 开发配置写入</div>
            <div class="layui-card-body">
                <form action="" class="layui-form" >
                
                    <fieldset class="layui-elem-field">
                        <legend>上传配置</legend>
                        <div class="layui-field-box">
                            <div class="layui-form-item">
                                <label class="layui-form-label">OSS阿里</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" name="oss_open" value="1" lay-text="On|Off" lay-skin="switch" lay-filter="oss_switch">
                                </div>
                            </div>
                            <div id="oss_box" style="display: none;">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">上传目录名</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="oss_dir" value="" placeholder="请输入上传目录名" class="layui-input">
                                    </div>
                                    <div class="layui-input-block layui-form-intro">
                                        <div class="layui-form-mid layui-word-aux">OSS上传目录应该按照项目名称分项目存储, 命名格式以字母开头，可以为字母和数字</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-field-box">
                            <div class="layui-form-item">
                                <label class="layui-form-label">COS腾讯</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" name="cos_open" value="1" lay-text="On|Off" lay-skin="switch" lay-filter="cos_switch">
                                </div>
                            </div>
                            <div id="cos_box" style="display: none;">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">上传目录名</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="cos_dir" value="" placeholder="请输入上传目录名" class="layui-input">
                                    </div>
                                    <div class="layui-input-block layui-form-intro">
                                        <div class="layui-form-mid layui-word-aux">COS上传目录应该按照项目名称分项目存储, 命名格式以字母开头，可以为字母和数字</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-field-box">
                            <div class="layui-form-item">
                                <label class="layui-form-label">AWS亚马逊</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" name="aws_open" value="1" lay-text="On|Off" lay-skin="switch" lay-filter="aws_switch">
                                </div>
                            </div>
                            <div id="aws_box" style="display: none;">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">上传目录名</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="aws_dir" value="" placeholder="请输入上传目录名" class="layui-input">
                                    </div>
                                    <div class="layui-input-block layui-form-intro">
                                        <div class="layui-form-mid layui-word-aux">AWS上传目录应该按照项目名称分项目存储, 命名格式以字母开头，可以为字母和数字</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-field-box">
                            <div class="layui-form-item">
                                <label class="layui-form-label">七牛云储存</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" name="qiniu_open" value="1" lay-text="On|Off" lay-skin="switch" lay-filter="qiniu_switch">
                                </div>
                            </div>
                        </div>
                        <div class="layui-field-box">
                            <div class="layui-form-item">
                                <label class="layui-form-label">本地上传</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" name="local_open" value="1" lay-text="On|Off" lay-skin="switch" lay-filter="local_switch">
                                </div>
                            </div>
                            <div id="local_box" style="display: none;">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">上传目录名</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="local_dir" value="static/upload" placeholder="请输入上传目录名" class="layui-input">
                                    </div>
                                    <div class="layui-input-block layui-form-intro">
                                        <div class="layui-form-mid layui-word-aux">本地上传目录，入口public目录下  注意写入权限</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </fieldset>

                    <fieldset class="layui-elem-field">
                        <legend>开发环境配置</legend>
                        <div class="layui-field-box">
                            <div class="layui-form-item">
                                <label class="layui-form-label">DB_HOST</label>
                                <div class="layui-input-block">
                                    <input type="text" name="develop[db_host]" value="127.0.0.1" lay-verify="required" placeholder="数据库连接地址" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">DB_PORT</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="develop[db_port]" value="3306" lay-verify="required" placeholder="数据库端口" class="layui-input">
                                </div>
                                <label class="layui-form-label">DB_CHAR</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="develop[db_char]" value="utf8mb4" lay-verify="required" placeholder="数据库编码" class="layui-input">
                                </div>
                                <label class="layui-form-label">DB_NAME</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="develop[db_name]" value="" lay-verify="required" placeholder="数据库名称" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">DB_USER</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="develop[db_user]" value="root" lay-verify="required" placeholder="数据库账号" class="layui-input">
                                </div>
                                <label class="layui-form-label">DB_PASS</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="develop[db_pass]" value="root" placeholder="数据库密码" class="layui-input">
                                </div>
                                <label class="layui-form-label">DB_PRE</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="develop[db_pre]" value="" lay-verify="required" placeholder="数据表前缀" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">REDIS_HOST</label>
                                <div class="layui-input-block">
                                    <input type="text" name="develop[redis_host]" value="r-bp18vmtk1409q08i00.redis.rds.aliyuncs.com" lay-verify="required" placeholder="redis连接地址" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">REDIS_PORT</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="develop[redis_port]" value="6379" lay-verify="required" placeholder="redis端口" class="layui-input">
                                </div>
                                <label class="layui-form-label">REDIS_PASS</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="develop[redis_pass]" value="1yVXE0uOItLIBCE" placeholder="redis密码" class="layui-input">
                                </div>
                                <label class="layui-form-label">REDIS_INDEX</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="develop[redis_index]" value="" lay-verify="required" placeholder="redis库" class="layui-input">
                                </div>

                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">登录账号</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="develop[username]" value="admin" lay-verify="required" placeholder="管理员账号" class="layui-input">
                                </div>
                                <label class="layui-form-label">登录密码</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="develop[password]" value="wangc002123" lay-verify="required" placeholder="管理员密码" class="layui-input">
                                </div>
             
                                
                            </div>
                        </div>
                    </fieldset>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn layui-btn-normal" lay-submit="">写入开发配置</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <div class="layui-col-md1"></div>
    </div>
</div>
<script src="//unpkg.com/layui@2.9.8/dist/layui.js"></script>
<script>
    layui.use(['form'], function() {
        var form = layui.form;
        var $    = layui.$;

        form.render();

        form.on('switch(oss_switch)', function(data) {
            if($(data.elem).prop('checked')) {
                $('#oss_box').show();
            }else {
                $('#oss_box').hide();
            }
        });

        form.on('switch(cos_switch)', function(data) {
            if($(data.elem).prop('checked')) {
                $('#cos_box').show();
            }else {
                $('#cos_box').hide();
            }
        });

        form.on('switch(aws_switch)', function(data) {
            if($(data.elem).prop('checked')) {
                $('#aws_box').show();
            }else {
                $('#cos_box').hide();
                $('#oss_box').hide();
                $('#aws_box').hide();
            }
        });

        form.on('switch(local_switch)', function(data) {
            if($(data.elem).prop('checked')) {
                $('#local_box').show();
            }else {
                $('#cos_box').hide();
                $('#oss_box').hide();
                $('#aws_box').hide();
                $('#local_box').hide();
            }
        });

        form.on('submit()', function (data) {
            if ($(this).hasClass('layui-btn-disabled')) {
                return false;
            }
            var _data = data.field;
            var loading = layer.msg('正在安装...', {
                icon: 16,
                shade: 0.2,
                time: false
            });
            $.ajax({
                url: window.location.href,
                type: 'post',
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                dataType: "json",
                data: _data,
                timeout: 60000,
                success: function (data) {
                    layer.close(loading);
                    if (data.code === 1) {
                        layer.msg(data.msg, {icon: 1}, function () {
                            // window.location.href = location.protocol + '//' + location.host + '/' + data.url;
                            window.location.href =  data.url;
                        });
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                },
                error: function (xhr, textstatus, thrown) {
                    layer.close(loading);
                    layer.msg('Status:' + xhr.status + '，' + xhr.statusText + '，请稍后再试！', {icon: 2});
                    return false;
                }
            });
            return false;
        });
    });
</script>
</html>
